package router

import (
	"editor/controller"
	"editor/controller/admin"
	"editor/middleware"
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	"time"
)

func InitRouter(router *gin.Engine) {

	// 静态资源加载，本例为css,js以及资源图片

	staticGroup := router.Group("/")
	staticGroup.Use(middleware.StaticFSCache)
	staticGroup.StaticFS("/editor.md", http.Dir("./static/editor.md"))
	staticGroup.StaticFS("/js", http.Dir("./static/js"))
	staticGroup.StaticFS("/css", http.Dir("./static/css"))
	staticGroup.StaticFS("/images", http.Dir("./static/images"))
	staticGroup.StaticFS("/markdown", http.Dir("./static/markdown"))
	staticGroup.StaticFile("/favicon.ico", "./static/favicon.ico")

	// 自定义模板函数，必须在加载模板前
	router.SetFuncMap(template.FuncMap{
		"ShowMDName4Nav": func(str string) string {
			if len(str) <= 3 || str[len(str)-3:] != ".md" {
				return str
			}
			return str[:len(str)-3]
		},
		"SafeHTML": func(s string) template.HTML {
			return template.HTML(s) //不转义HTML
		},
		"TimeZone2Str": func(i int64) string {
			return time.Unix(i, 0).Format("2006-01-02 15:04:05")
		},
		"ShowDisableStatus": func(isDisable int) string {
			if isDisable == 1 {
				return "已删除"
			} else {
				return "启用中"
			}
		},
		"listIsNoEpt": func(list []interface{}) bool {
			return len(list) > 0
		},
	})

	// 导入所有模板，多级目录结构需要这样写
	router.LoadHTMLGlob("template/*")

	// indexGroup
	indexGroup := router.Group("/")
	{
		indexGroup.GET("/", controller.IndexHandler)
		indexGroup.GET("/read/:id", controller.IndexHandler)

		indexGroup.GET("/login", controller.LoginHandler)
		indexGroup.POST("/login", controller.DoLoginHandler)
	}

	// adminGroup
	adminGroup := router.Group("/admin")
	adminGroup.Use(middleware.CheckIsLogin())
	{
		adminGroup.GET("/", admin.ListHandler)
		adminGroup.GET("/logout", admin.LogoutHandler)
		adminGroup.GET("/edit/:id", admin.EditHandler)
		adminGroup.POST("/save/:id", admin.SaveContentHandler)
		adminGroup.POST("/add-file", admin.AddFileHandler)
		adminGroup.POST("/add-dir", admin.AddDirHandler)
		adminGroup.POST("/image-paste-upload", admin.ImagePasteUploadHandler)
		adminGroup.POST("/sort", admin.SortHandler)
		adminGroup.POST("/rename", admin.RenameHandler)
		adminGroup.POST("/delete", admin.DeleteHandler)
	}
}
